package com.project.class4_7;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest {
    //创建一个Lock锁对象
    private Lock lockObj=new ReentrantLock();
    public void foo(){
//        lockObj.lock();
            try {
                //尝试拿起锁，如果拿起失败，表示锁已被其他线程拿起，返回false
                if (lockObj.tryLock()){
                for (int i = 0; i < 10; i++) {
                    //打印当前线程对象
                    System.out.println(Thread.currentThread() + "   " + i);
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }}
                }else {
                    System.out.println("锁获取失败");
                }
        }finally {
            lockObj.unlock();
        }
    }
}
